package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserUtil implements UserDao {
	private Connection conn;
	private PreparedStatement userQuery;
	private ResultSet rs;
	@Override
	public int add(Useinfo userinfo) {
		int result=0;
		try {
		conn=DBcon.getConnection();
		String sql="insert into userinfo (username,name,age,sex,birthday,place,email,phone) values(?,?,?,?,?,?,?,?)";
		userQuery=conn.prepareStatement(sql);
		userQuery.setString(1,userinfo.getUsername());
		userQuery.setString(2,userinfo.getName());
		userQuery.setInt(3,userinfo.getAge());
		userQuery.setString(4,userinfo.getSex());
		userQuery.setString(5,userinfo.getBirthday());
		userQuery.setString(6,userinfo.getPlace());
		userQuery.setString(7,userinfo.getEmail());
		userQuery.setString(8, userinfo.getPhone());
		
		result=userQuery.executeUpdate();
		}catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			DBcon.closeConnection(conn);
			DBcon.closeResult(rs);
			DBcon.closeStatement(userQuery);
		}
		return result;
	}
	
	@Override
	public int update(Useinfo userinfo) {
		int result=0;
		try {
			conn=DBcon.getConnection();
			String sql="update userinfo set name=?,age=?,sex=?,birthday=?,place=?,email=?,phone=? where username=?";
			userQuery=conn.prepareStatement(sql);
			userQuery.setString(1,userinfo.getName());
			userQuery.setInt(2,userinfo.getAge());
			userQuery.setString(3,userinfo.getSex());
			userQuery.setString(4, userinfo.getBirthday());
			userQuery.setString(5,userinfo.getPlace());
			userQuery.setString(6,userinfo.getEmail());
			userQuery.setString(7,userinfo.getPhone());
			userQuery.setString(8,userinfo.getUsername());
			
			result=userQuery.executeUpdate();
		}catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			DBcon.closeConnection(conn);
			DBcon.closeResult(rs);
			DBcon.closeStatement(userQuery);
		}
		return result;
	}

	@Override
	public Useinfo findbyUsername(String username) {
		Useinfo userinfo=null;
		try {
			conn=DBcon.getConnection();
			String sql="select * from userinfo where username='"+username+"'";
			userQuery=conn.prepareStatement(sql);
			rs=userQuery.executeQuery();
			if(rs.next()) {
				userinfo=new Useinfo();
				userinfo.setUsername(rs.getString("username"));
				userinfo.setName(rs.getString("name"));
				userinfo.setSex(rs.getString("sex"));
				userinfo.setAge(rs.getInt("age"));
				userinfo.setBirthday(rs.getString("birthday"));
				userinfo.setPlace(rs.getString("place"));
				userinfo.setEmail(rs.getString("email"));
				userinfo.setPhone(rs.getString("phone"));
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			DBcon.closeConnection(conn);
			DBcon.closeResult(rs);
			DBcon.closeStatement(userQuery);
		}
		
		return userinfo;
		
	}

}
